package com.fxc.crowd.service.impl;

import com.fxc.crowd.constant.CrowdConstant;
import com.fxc.crowd.entity.po.AdminPO;
import com.fxc.crowd.entity.po.AdminPOExample;
import com.fxc.crowd.entity.po.AdminPOExample.Criteria;
import com.fxc.crowd.exception.LoginAcctAlreadyInUseException;
import com.fxc.crowd.exception.LoginAcctAlreadyInUseforUpdateException;
import com.fxc.crowd.exception.LoginFailedException;
import com.fxc.crowd.mapper.AdminPOMapper;
import com.fxc.crowd.service.api.AdminService;
import com.fxc.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminPOMapper adminPOMapper;

    private Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    @Override
    public void saveAdmin(AdminPO adminPO) {

        // 1.密码加密
        String userPswd = adminPO.getUserPswd();
        // userPswd = CrowdUtil.md5(userPswd);
        userPswd = passwordEncoder.encode(userPswd);
        adminPO.setUserPswd(userPswd);

        // 2.生成创建时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(date);
        adminPO.setCreateTime(createTime);

        // 3.执行保存
        try {
            adminPOMapper.insert(adminPO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("异常全类名=" + e.getClass().getName());
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }

    }

    @Override
    public List<AdminPO> getAll() {
        return adminPOMapper.selectByExample(new AdminPOExample());
    }

    @Override
    public AdminPO getAdminByLoginAcct(String loginAcct, String userPswd) {

        // 1.根据登录账号查询AdminPo对象
        AdminPOExample adminPOExample = new AdminPOExample();

        Criteria criteria = adminPOExample.createCriteria();

        criteria.andLoginAcctEqualTo(loginAcct);

        List<AdminPO> adminPOS = adminPOMapper.selectByExample(adminPOExample);

        // 2.判断Admin对象是否为null
        if (adminPOS == null || adminPOS.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        if (adminPOS.size() > 1) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_ERROR_LOGIN_NOT_UNIQUE);
        }

        AdminPO adminPO = adminPOS.get(0);

        // 3.如果Admin为null则抛出异常
        if (adminPO == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 4.如果不为null则将数据库密码从AdminPo对象中取出
        String userPswdDB = adminPO.getUserPswd();

        // 5.将表单提交的文明密码进行加密
        //String userPswdFrom = CrowdUtil.md5(userPswd);

        System.out.println(passwordEncoder.encode(userPswd));

        //boolean matches = passwordEncoder.matches(userPswd, userPswdDB);

        // 6.对密码进行比较
        if (!passwordEncoder.matches(userPswd, userPswdDB)) {
            logger.info("这里抛出异常");
            // 7.如比较结果不一致则抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 8.如果一致则返回Admin对象
        return adminPO;
    }

    @Override
    public PageInfo<AdminPO> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {

        // 1.调用PageHelper的静态方法开启分页功能
        // 这里体现了pageHelper的“非浸入式”设计：原本要做的查询不必有任何修改
        PageHelper.startPage(pageNum, pageSize);

        // 2.执行查询
        List<AdminPO> list = adminPOMapper.selectAdminByKeyword(keyword);
        // 3.封装到PageInfo当中
        return new PageInfo<AdminPO>(list);
    }

    @Override
    public void remove(Integer adminId) {
        adminPOMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public AdminPO getAdminById(Integer adminId) {
        return adminPOMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void update(AdminPO adminPO) {

        //Selective表示有选择的更新，对于null值字段不更新
        try {
            adminPOMapper.updateByPrimaryKeySelective(adminPO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("异常全类名=" + e.getClass().getName());
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseforUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {

        // 1.根据adminId删除旧的关联数据
        adminPOMapper.deleteOldRelationship(adminId);

        // 2.根据roleIdList和adminId保存新的关联关系
        if (roleIdList != null && roleIdList.size() > 0) {
            adminPOMapper.insertNewRelationship(adminId, roleIdList);
        }
    }

    @Override
    public AdminPO getAdminByLoginAcct(String username) {

        AdminPOExample example = new AdminPOExample();

        Criteria criteria = example.createCriteria();

        criteria.andLoginAcctEqualTo(username);

        List<AdminPO> list = adminPOMapper.selectByExample(example);

        AdminPO admin = list.get(0);

        return admin;
    }
}
